package com.slkj.service;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.slkj.dto.SpecialDutyParam;
import com.slkj.dto.SpecialTaskDTO;
import com.slkj.dto.UserinfoDTO;
import com.slkj.entity.*;
import com.slkj.mapper.*;
import org.activiti.bpmn.model.Activity;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.TaskServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName SpecialService.java
 * @Description TODO
 * @createTime 2020年03月12日 11:27:00
 */
@Service
public class SpecialService {

    private Logger log = LoggerFactory.getLogger(SpecialService.class);

    @Autowired
    ProcessEngine processEngine;


    @Autowired
    RepositoryService repositoryService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    HistoryService historyService;

    @Autowired
    TaskService taskService;

    @Autowired
    SpecialTaskMapper specialTaskMapper;

    @Autowired
    SpecialNodeMapper specialNodeMapper;

    @Autowired
    FileMapper fileMapper;
    @Autowired
    SpecialDutyMapper specialDutyMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    LeaderIdeaMapper leaderIdeaMapper;

    @Autowired
    UserService userService;


    public void createTask(SpecialTask specialTask, String username) {

        List<SpecialNode> specialNodeList = specialTask.getSpecialNodeList();
        List<String> specialDutyParamList = specialTask.getSpecialDutyParamList();
        if (specialNodeList == null || specialDutyParamList == null) {
            throw new NullPointerException("空指针异常");
        }
        if (specialNodeList.size() == 0 || specialDutyParamList.size() == 0) {
            throw new NullPointerException("空指针异常");

        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        for (SpecialNode specialNode : specialNodeList) {
            List<String> projectTime = specialNode.getProjectTime();
            try {
                specialNode.setSpecialBeginTime(simpleDateFormat.parse(projectTime.get(0)));
                specialNode.setSpecialEndTime(simpleDateFormat.parse(projectTime.get(1)));
            } catch (ParseException e) {
                log.error("日期格式转换异常");
                e.printStackTrace();
                throw new RuntimeException("日期格式转换异常");
            }
        }
        Userinfo userinfo = userMapper.selectByUsername(username);
        UserinfoDTO userinfoDTO = userService.getUserinfo(userinfo.getId());
        String type = userinfoDTO.getType();
        if (StringUtils.isBlank(type)) {
            throw new RuntimeException("任务发起人type为空");
        }
        specialTask.setUsername(userinfoDTO.getUsername());
        specialTask.setUserType(type);
        List<Userinfo> userinfoList = userMapper.selectByUserIdList(specialDutyParamList);


        specialTaskMapper.insert(specialTask);
        for (SpecialNode specialNode : specialNodeList) {
            specialNode.setSpecialTaskId(specialTask.getId());
            specialNodeMapper.insert(specialNode);
            List<File> fileList = specialNode.getFileList();
            for (Userinfo userinfoSelect : userinfoList) {
                SpecialDuty specialDuty = new SpecialDuty();
                specialDuty.setUserId(userinfoSelect.getId());
                specialDuty.setSpecialTaskId(specialTask.getId());
                specialDuty.setSpecialNodeId(specialNode.getId());
                specialDuty.setName(userinfoSelect.getName());
                specialDuty.setUsername(userinfoSelect.getUsername());
                specialDuty.setSpecialAuditStatus("待上传");
                specialDuty.setSpecialLight("灰灯");
                specialDuty.setSpecialYear(specialTask.getSpecialYear());
                specialDutyMapper.insert(specialDuty);
                if (fileList != null & fileList.size() != 0) {
                    fileMapper.insertSpecialDuty(fileList, specialDuty.getId(), 1);
                }
                Map map = new HashMap();
                map.put("specialName", userinfoSelect.getUsername());
                runtimeService.startProcessInstanceByKey("Special", specialDuty.getClass().getSimpleName().toLowerCase() + "/" + specialDuty.getId(), map);
                taskComplete(null, 1, specialDuty.getId());

            }
        }

    }

    private void taskComplete(List<Map> mapList, int count, String dutyId) {
        SpecialDuty specialDuty = specialDutyMapper.selectByDutyId(dutyId);
        String buniessKey = specialDuty.getClass().getSimpleName().toLowerCase() + "/" + specialDuty.getId();
        String buniessKeyLight = specialDuty.getClass().getSimpleName().toLowerCase() + "light/" + specialDuty.getId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKey).singleResult();
        ProcessInstance processInstanceLight = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKeyLight).singleResult();
        ProcessInstance processInstanceTask = null;
        if (processInstance != null) {
            processInstanceTask = processInstance;
        } else if (processInstanceLight != null) {
            processInstanceTask = processInstanceLight;
        } else {
            throw new ActivitiException("找不到流程实例");
        }
        for (int i = 0; i < count; i++) {
            Task task = taskService.createTaskQuery().processInstanceId(processInstanceTask.getProcessInstanceId()).taskAssignee(specialDuty.getUsername()).singleResult();
            if (mapList != null && mapList.size() != 0) {
                if (mapList.get(count - 1) != null) {
                    taskService.complete(task.getId(), mapList.get(count - 1));
                } else {
                    taskService.complete(task.getId());
                }
            } else {
                taskService.complete(task.getId());
            }
        }

    }


    public PageInfo<SpecialTaskDTO> getTaskFeedback(String specialTitle, String specialIndexSource, Date beginDate, Date endDate, String specialLight, String username, int gotoPage, int pageSize
            , String submitUnit, String leader, String status) {
//        Userinfo userinfo = userMapper.selectByUsername(username);
//        UserinfoDTO userinfoDTO = userService.getUserinfo(userinfo.getId());
//        if (userinfoDTO != null && StringUtils.isBlank(userinfoDTO.getType())) {
//            userinfoDTO.getType();
//        }


        PageHelper.startPage(gotoPage, pageSize, true);
        List<SpecialTaskDTO> specialTaskDTOList = specialDutyMapper.selectSpecialTaskDTO(specialTitle, specialIndexSource, beginDate, endDate, specialLight, username, submitUnit, leader, status);
        PageInfo<SpecialTaskDTO> pageInfo = new PageInfo<>(specialTaskDTOList);


        if (specialTaskDTOList != null && specialTaskDTOList.size() != 0) {
            List<File> specialFileList = fileMapper.selectBySpecialTaskDTOList(specialTaskDTOList);
            List<File> specialAddFileList = fileMapper.selectAddFileUrl(specialTaskDTOList);

            for (SpecialTaskDTO specialTaskDTO : specialTaskDTOList) {
                int count = leaderIdeaMapper.selectCountSpecial(specialTaskDTO, 1);
                specialTaskDTO.setLeaderCount(count);
            }

            if (specialFileList != null && specialFileList.size() != 0) {
                for (SpecialTaskDTO specialTaskDTO : specialTaskDTOList) {
                    boolean result = false;
                    List<File> specialFiles = new ArrayList<>();
                    for (File specialFile : specialFileList) {
                        if (specialTaskDTO.getId().equals(specialFile.getDutyId())) {
                            result = true;
                            specialFiles.add(specialFile);
                        }
                    }
                    if (result) {
                        specialTaskDTO.setFileList(specialFiles);
                    }
                }
            }


            if (specialAddFileList != null && specialAddFileList.size() != 0) {
                for (SpecialTaskDTO specialTaskDTO : specialTaskDTOList) {
                    boolean result = false;
                    List<File> specialFiles = new ArrayList<>();
                    for (File specialFile : specialAddFileList) {
                        if (specialTaskDTO.getId().equals(specialFile.getDutyId())) {
                            if (specialFile.getAddDutyUrl() != null && "".equals(specialFile.getAddDutyUrl())) {
                                result = true;
                                specialFiles.add(specialFile);
                            }
                        }
                    }
                    if (result) {
                        specialTaskDTO.setAddFileList(specialFiles);
                    }
                }
            }
        }

        return pageInfo;
    }

    public void taskUpload(List<File> fileList, String username, String dutyId, String type, List<Map> mapList, String count) {
        fileMapper.insertSpecialDuty(fileList, dutyId, Integer.parseInt(type));
        SpecialDuty specialDuty = specialDutyMapper.selectByDutyId(dutyId);
        if (!specialDuty.getSpecialAuditStatus().equals("待上传") && !specialDuty.getSpecialAuditStatus().equals("未通过待上传")) {
            throw new RuntimeException("不能上传文件");
        }
        taskComplete(mapList, Integer.parseInt(count), dutyId);
        specialDutyMapper.updateStatusById("浅绿灯", "待审核", dutyId);
        specialDutyMapper.updateSubmitTime(new Date(), dutyId);
    }

    public void passTask(List<String> dutyIdList, List<Map> mapList, String count, String specialAuditIdea) {
        for (String dutyId : dutyIdList) {
            log.info("----------------------------->>> public void passTask(String dutyId) ");
            String id = SpecialDuty.class.getSimpleName().toLowerCase() + "/" + dutyId;
            SpecialDuty specialDuty = specialDutyMapper.selectByDutyId(dutyId);
            if (specialDuty == null) {
                throw new NullPointerException("空指针异常");
            }
            SpecialTask specialTask = specialTaskMapper.selectByDutyId(specialDuty.getSpecialTaskId());

            if (specialTask == null) {
                throw new NullPointerException("空指针异常");
            }
            //任务审核
            taskComplete(mapList, Integer.parseInt(count), dutyId);
            specialDutyMapper.updateStatusById("绿灯", "通过", dutyId);
            specialDutyMapper.updateAuditIdea(specialAuditIdea, dutyId);
        }
    }

    public void noPassTask(List<String> dutyIdList, List<Map> mapList, String count, String specialAuditIdea) {
        for (String dutyId : dutyIdList) {
            log.info("----------------------------->>> public void passTask(String dutyId) ");
            String id = SpecialDuty.class.getSimpleName().toLowerCase() + "/" + dutyId;
            SpecialDuty specialDuty = specialDutyMapper.selectByDutyId(dutyId);
            if (specialDuty == null) {
                throw new NullPointerException("空指针异常");
            }
            SpecialTask specialTask = specialTaskMapper.selectByDutyId(specialDuty.getSpecialTaskId());

            if (specialTask == null) {
                throw new NullPointerException("空指针异常");
            }
            //任务审核
            taskComplete(mapList, Integer.parseInt(count), dutyId);
            specialDutyMapper.updateStatusById("黄灯", "未通过待上传", dutyId);
            specialDutyMapper.updateAuditIdea(specialAuditIdea, dutyId);
        }

    }

    public void lightAdjust(List<String> dutyIdList, String light, List<Map> mapList, String count, String lightCause) {
        for (String dutyId : dutyIdList) {
            //事先dutyId根据查出当前灯的状态
            SpecialDuty specialDuty = specialDutyMapper.selectByDutyId(dutyId);
            if (specialDuty == null) {
                throw new NullPointerException("空指针异常");
            }
//        SpecialTask specialTask = specialTaskMapper.selectByDutyId(specialDuty.getSpecialTaskId());
//
//        if (specialTask == null) {
//            throw new NullPointerException("空指针异常");
//        }
//        specialTaskMapper.selectByDutyId(specialDuty.getId());

            String specialLight = specialDuty.getSpecialLight();
            if (specialLight.equals(light)) {
                return;
            } else {
                ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(specialDuty.getClass().getSimpleName().toLowerCase() + "/" + dutyId).singleResult();
                ProcessInstance processInstancelight = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(specialDuty.getClass().getSimpleName().toLowerCase() + "light/" + dutyId).singleResult();

                if (processInstance != null) {
                    runtimeService.deleteProcessInstance(processInstance.getProcessInstanceId(), "processInstance delete");
                }
                if (processInstancelight != null) {
                    runtimeService.deleteProcessInstance(processInstancelight.getProcessInstanceId(), "processInstance delete");
                }

                mapList.get(0).put("specialName", specialDuty.getUsername());
                runtimeService.startProcessInstanceByKey("Speciallight", specialDuty.getClass().getSimpleName().toLowerCase() + "light/" + dutyId, mapList.get(0));
//            taskComplete(mapList, Integer.parseInt(), dutyId);
                specialDutyMapper.updateStatusById(light, mapList.get(0).get("isPass") + "", dutyId);
                specialDutyMapper.updateLightCause(lightCause, dutyId);
                specialDutyMapper.updateSubmitTime(new Date(), dutyId);

            }
        }
    }


    public List<LeaderIdea> getLeaderIdea(String dutyId) {
        List<LeaderIdea> leaderIdeaList = leaderIdeaMapper.selectLeaderIdea(dutyId, 1);
        return leaderIdeaList;
    }
}
